package com.qiche.util;

import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * fastFDS上传文件工具类
 *
 * @author chendezhi
 * @date 2018/2/26 10:26
 */
@Component
public class FastDFSUtils {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    static {
        try {
            ClientGlobal.init("fdfs_client.conf");
            System.out.println("ClientGlobal.configInfo():::::::::" + ClientGlobal.configInfo());
            //tracker客户端
            TrackerClient trackerClient = new TrackerClient();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
    }


    /**
     * 上传图片
     *
     * @param pic 图片
     * @return
     * @throws Exception
     */
    public static String uploadPic(MultipartFile pic) throws Exception {


        //创建一个NUll值 的Stage的服务端
        StorageServer storageServer = null;
        //tracker客户端
        TrackerClient trackerClient = new TrackerClient();
        //与Tracker连接
        TrackerServer trackerServer = trackerClient.getConnection();
        //创建Stoage的客户端
        StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);

        String ext = FilenameUtils.getExtension(pic.getOriginalFilename());

        NameValuePair[] meta_list = new NameValuePair[3];

        //图片原始名
        meta_list[0] = new NameValuePair("filename", pic.getOriginalFilename());
        //图片大小
        meta_list[1] = new NameValuePair("filelength", String.valueOf(pic.getSize()));
        //图片扩展名
        meta_list[2] = new NameValuePair("ext", ext);

        //上传图片
        //http://192.168.200.128/group1/M00/00/01/wKjIgFWOYc6APpjAAAD-qk29i78248.jpg
        String path = storageClient1.upload_file1(pic.getBytes(), ext, meta_list);
        trackerServer.close();

        return path;
    }
    public static String uploadFilePic(File pic) throws Exception {


        //创建一个NUll值 的Stage的服务端
        StorageServer storageServer = null;
        //tracker客户端
        TrackerClient trackerClient = new TrackerClient();
        //与Tracker连接
        TrackerServer trackerServer = trackerClient.getConnection();
        //创建Stoage的客户端
        StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);

        String ext = FilenameUtils.getExtension(pic.getName());

        NameValuePair[] meta_list = new NameValuePair[3];

        //图片原始名
        meta_list[0] = new NameValuePair("filename", pic.getName());
        //图片大小
        meta_list[1] = new NameValuePair("filelength", String.valueOf(pic.length()));
        //图片扩展名
        meta_list[2] = new NameValuePair("ext", ext);

        //上传图片
        //http://192.168.200.128/group1/M00/00/01/wKjIgFWOYc6APpjAAAD-qk29i78248.jpg
        String path = storageClient1.upload_file1(getBytes(pic), ext, meta_list);
        trackerServer.close();

        return path;
    }
    private static byte[] getBytes(File file){
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }
    public String[] uploadFileByStream(InputStream inStream, String uploadFileName, long fileLength) throws IOException {

        String[] results = null;
        String fileExtName = "";
        if (uploadFileName.contains(".")) {
            fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
        } else {
            logger.warn("Fail to upload file, because the format of filename is illegal.");
            return results;
        }
        //tracker客户端
        TrackerClient trackerClient = new TrackerClient();
        //与Tracker连接
        TrackerServer trackerServer = trackerClient.getConnection();
        StorageServer storageServer = null;
        StorageClient1 client = new StorageClient1(trackerServer, storageServer);

        NameValuePair[] metaList = new NameValuePair[3];
        metaList[0] = new NameValuePair("fileName", uploadFileName);
        metaList[1] = new NameValuePair("fileExtName", fileExtName);
        metaList[2] = new NameValuePair("fileLength", String.valueOf(fileLength));

        try {
            // results[0]: groupName, results[1]: remoteFilename.
            System.out.println("uploadFileByStream::fileLength=====" + fileLength);
            results = client.upload_file(null, fileLength, new UploadStream(inStream, fileLength), fileExtName, metaList);
            if (results != null) {
                for (String result : results) {
                    System.out.println(result);
                }
            }
        } catch (Exception e) {
            System.out.println("FASTDFS出现错误");
            e.printStackTrace();
            logger.warn("Upload file \"" + uploadFileName + "\"fails");
        } finally {
            trackerServer.close();
            inStream.close();
        }
        return results;
    }

    /**
     * download file from storage server
     *
     * @param group_name      the group name of storage server
     * @param remote_filename filename on storage server
     * @return file content/buff, return null if fail
     */
    public byte[] download_file(String group_name, String remote_filename) throws IOException, MyException {
        //tracker客户端
        TrackerClient trackerClient = new TrackerClient();
        //与Tracker连接
        TrackerServer trackerServer = trackerClient.getConnection();

        StorageServer storageServer = null;
        StorageClient1 client = new StorageClient1(trackerServer, storageServer);
        byte[] bytes = client.download_file(group_name, remote_filename);
        return bytes;
    }




}
